package com.xln.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xln.pojo.Article;
import com.xln.pojo.Category;
import com.xln.pojo.Tag;
import com.xln.service.ArticleService;
import com.xln.service.CategoryService;
import com.xln.util.ResEnum;
import com.xln.DTO.CategoryAddDTO;
import com.xln.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class CategoryController {
    
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ArticleService articleService;

//查询所有分类    （渲染到分类列表页面）
    @GetMapping("/categories")
    public String categoriesPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            Model model) {
        
        // 获取所有分类（树形结构）
        List<Category> categoryTree = categoryService.getCategoryTree();
        
        // 分页获取分类列表
        Page<Category> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("order_num");
        Page<Category> categoryPage = categoryService.page(page, queryWrapper);

        model.addAttribute("categoryTree", categoryTree);
        model.addAttribute("categoryPage", categoryPage);
        
        return "categories";
    }

//    查询所有分类    （ajax请求）
    @ResponseBody
    @GetMapping("/categoriesAjax")
    public Result<List<Category>> categoriesPageAjax() {

        // 获取分类列表
        List<Category> categories = categoryService.list();

//        model.addAttribute("categoryTree", categoryTree);
//        model.addAttribute("categoryPage", page);

        return Result.success(ResEnum.SUCCESS, categories);
    }

//    添加分类
    @ResponseBody
    @PostMapping("/addCategory")
    public ResEnum addCategory(
            @RequestBody CategoryAddDTO categoryAddDTO,
            Model model) {
            Category category = new Category();
            category.setName(categoryAddDTO.getName());
            category.setParentId(categoryAddDTO.getParentId());
            category.setDescription(categoryAddDTO.getDescription());

        boolean saveResult = categoryService.save(category);

        if (saveResult) {
            return ResEnum.SUCCESS;
        } else {
//            model.addAttribute("message", "添加失败");
            return ResEnum.ERROR;
        }
    }

    @ResponseBody
    @PostMapping("/deleteCategory")
    public ResEnum deleteCategory(
            @RequestBody Map<String, Object> params) {
        Long id = Long.parseLong(params.get("id").toString());
        Boolean deleteArticles = (Boolean) params.get("deleteArticles");

        Category category = categoryService.getById(id);
        if (category == null) {
//            model.addAttribute("message", "分类不存在");
            return ResEnum.ERROR;
        }

        if (deleteArticles){
            Boolean result = categoryService.deleteCategoryAndChildAndArticles(id);
            return ResEnum.SUCCESS;
        }else {

            Boolean result2 = categoryService.deleteCategoryAndChild(id);
            return ResEnum.SUCCESS;
        }

    }

    @ResponseBody
    @PostMapping("/updateCategory")
    public ResEnum updateCategory(
            @RequestBody Category category,
            Model model) {
        log.info("更新分类：{}", category);
        boolean result = categoryService.updateById(category);
        log.info("更新结果：{}", result);
        if (!result) {
//            model.addAttribute("message", "更新失败");
            return ResEnum.ERROR;
        }

        return ResEnum.SUCCESS;
    }

    @GetMapping("/getCategoryArtNum")
    @ResponseBody
    public Result<Integer> getCategoryArtNum(
            @RequestParam(defaultValue = "1") Long id) {
        Category category = categoryService.getById(id);
        if (category == null) {
            return Result.error();
        }

        List<Long> childIdsTree = categoryService.getChildIdsTree(id);
        int artNum = articleService.count(new QueryWrapper<Article>().lambda()
                .in(Article::getCategoryId, childIdsTree)
        );
        return Result.success(artNum);
    }

//    获取分类名称通过分类ID
    @GetMapping("/getArticleCategoryName/{id}")
    @ResponseBody
    public Result<String> getArticleCategoryName(
            @PathVariable("id") Long id) {
        Category category = categoryService.getById(id);
        if (category == null) {
            return Result.error(ResEnum.ERROR, "分类不存在");
        }
        log.info("分类名称：{}", category.getName());
        return Result.success(category.getName());
    }

    @GetMapping("/categoryArticle")
    public String articleCategory(
            @RequestParam(defaultValue = "1") Long id,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize,
            Model model) {
        List<Long> childIdsTree = categoryService.getChildIdsTree(id);
//        List<Article> articles = articleService.listByIds(childIdsTree);
        Page<Article> page = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<Article> queryWrapper = Wrappers.<Article>lambdaQuery()
                .in(Article::getCategoryId, childIdsTree)
                .eq(Article::getStatus, Article.ArticleStatus.PUBLISHED.getCode())
                .orderByDesc(Article::getCreateTime);

        Page<Article> articlePage = articleService.page(page, queryWrapper);

        model.addAttribute("articlePage", articlePage);

        Category category = categoryService.getById(id);
        model.addAttribute("category", category);

        List<Category> categoryTree = categoryService.getCategoryTree();
        model.addAttribute("categoryTree", categoryTree);

        return "categoryArticles";

    }


}
